<?php
namespace app\common\lib\module_config;

class TagRW
{

    public function getTag($moduleName, $fileName = null)
    {
        $directory = 'config/tag';
        if ($fileName != null) {
            $data = json_decode(getModuleConfig($moduleName, $directory, $fileName), true);
            return $data;
        } else {
            $dir  = ROOT_PATH . '/public/plugins/' . $moduleName . '/' . $directory;
            $list = [];
            if (is_dir($dir)) {
                if ($dh = opendir($dir)) {
                    while (($file = readdir($dh)) !== false) {
                        $exts = explode('.', $file);
                        $end  = end($exts);
                        if ($end == 'json') {
                            $list[] = $file;
                        }
                    }
                    closedir($dh);
                }
            }
            return $list;
        }
    }

    public function setTag($moduleName, $fileName, $data)
    {
        $return = saveModuleConfigData($moduleName, 'config/tag', $fileName, $data);
        return $return;
    }

    public static function traceConfig($trace, $tag = null)
    {
        $moduleName = $trace->getApp();
        $directory  = 'config/tag';
        $fileName   = $trace->getController() . '@' . $trace->getFunc() . ".json";
        $data       = json_decode(getModuleConfig($moduleName, $directory, $fileName), true);
        if (empty($data[$tag])) {
            $data[$tag] = [];
            saveModuleConfigData($moduleName, 'config/tag', $fileName, $data);
            $data = json_decode(getModuleConfig($moduleName, $directory, $fileName), true);
        }
        if ($tag != null) {
            $data = $data[$tag];
        }
        return $data;
    }

}
